package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.common.model.business.*;
import com.goods.common.response.ActiveUser;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.ProductVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class InStockServiceImpl implements InStockService {


    @Autowired
    private InStockMapper inStockMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private InStockInfoMapper inStockInfoMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    /**
     *  入库单（入库记录）数据分页列表展示
     * @return
     */
    @Override
    public PageVO<InStockVO> findInStockList(Map map) {

        //查询list
       List<InStock> inStockList = inStockMapper.findInStockList(map);


        List<InStockVO> inStockVOList = new ArrayList<>();
        if (inStockList != null){
            //封装成vo对象
            inStockVOList = inStockList.stream().map(inStock -> {
                InStockVO inStockVO = new InStockVO();
                BeanUtils.copyProperties(inStock, inStockVO);
                return inStockVO;
            }).collect(Collectors.toList());

            //遍历vo对象，并向里set用户来源数据
            for (InStockVO inStockVO : inStockVOList) {
                Supplier supplier = supplierMapper.selectByPrimaryKey(inStockVO.getSupplierId());
                if (supplier != null){
                    inStockVO.setSupplierName(supplier.getName());
                    inStockVO.setAddress(supplier.getAddress());
                    inStockVO.setEmail(supplier.getEmail());
                    inStockVO.setPhone(supplier.getPhone());
                    inStockVO.setSort(supplier.getSort());
                    inStockVO.setContact(supplier.getContact());
                }
            }
        }
        //封装page信息
        Integer pageNum = Integer.valueOf((String) map.get("pageNum"));
        Integer pageSize = Integer.valueOf((String) map.get("pageSize"));
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<InStockVO> pageInfo = new PageInfo<>(inStockVOList);
        //返回信息
        return new PageVO<InStockVO>(pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 明细显示
     * @param inStockId
     * @return
     */
    @Override
    public Map<String, Object> detail(Long inStockId, int pageNum) {

        //声明返回的Map
        Map<String, Object> map = new HashMap<>();
        //获取入库记录
        InStock inStock = inStockMapper.selectByPrimaryKey(inStockId);
        //判断
        if (inStock != null){
            //获取物资来源表
            Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
            if (supplier != null){
                SupplierVO supplierVO = new SupplierVO();
                BeanUtils.copyProperties(supplier,supplierVO);
                //封装到Map种
                map.put("supplierVO",supplierVO);
            }
            //根据 in_num获取product数据
            List<ProductVO> productList = productMapper.findByInnum(inStock.getInNum());
            //封装page对象
            PageHelper.startPage(pageNum,2);
            PageInfo<ProductVO> pageInfo = new PageInfo<>(productList);
            //set到Map中

            map.put("itemVOS",pageInfo.getList());
            map.put("total",pageInfo.getTotal());
            map.put("status",inStock.getStatus());

        }
        return map;
    }


    /**
     * 放入回收站
     * @param id
     */
    @Override
    public void remove(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock != null){
            inStock.setStatus(1);
            inStock.setModified(new Date());
            inStockMapper.updateByPrimaryKey(inStock);
        }
    }

    /**
     * 还原
     * @param id
     * @return
     */
    @Override
    public void back(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock != null){
            inStock.setStatus(0);
            inStock.setModified(new Date());
            inStockMapper.updateByPrimaryKey(inStock);
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    public void delete(Long id) {
        inStockMapper.deleteByPrimaryKey(id);
    }

    /**
     * add入库
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addIntoStock(InStockVO inStockVO) {
        if (inStockVO == null)
            return;
        //新增 instock
        InStock inStock = new InStock();
        //cope
        BeanUtils.copyProperties(inStockVO,inStock);
        //生成in_num 随机值
        inStock.setInNum(UUID.randomUUID().toString());
        //时间
        inStock.setCreateTime(new Date());
        inStock.setModified(new Date());
        //初始状态为未审核
        inStock.setStatus(2);
        //商品总数
        List<Map<String, Object>> productList = inStockVO.getProducts().stream().map(pro -> {
            Map<String, Object> product = (Map<String, Object>) pro;
            return product;
        }).collect(Collectors.toList());

        Integer number = 0;
        for (Map<String, Object> map : productList) {
            Integer productNumber = Integer.valueOf(map.get("productNumber").toString());
            number += productNumber;
        }
        inStock.setProductNumber(number);
        //赋值用户名
        ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
        inStock.setOperator(activeUser.getUser().getUsername());
        //新增
        inStockMapper.insert(inStock);

        //新增完之后，要在中间表插入数据
        for (Map<String, Object> map : productList) {
            Integer productId = (Integer) map.get("productId");
            Integer productNumber = (Integer) map.get("productNumber");

            Product product = productMapper.selectByPrimaryKey(productId);
            InStockInfo inStockInfo = new InStockInfo();
            //set值
            inStockInfo.setCreateTime(new Date());
            inStockInfo.setProductNumber(productNumber);
            inStockInfo.setInNum(inStock.getInNum());
            inStockInfo.setPNum(product.getPNum());
            inStock.setModified(new Date());
            //添加
            inStockInfoMapper.insert(inStockInfo);
        }
    }


    /**
     * 审核通过
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publish(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        if (inStock != null){
            //判断库存
            Example example = new Example(InStockInfo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("inNum",inStock.getInNum());
            List<InStockInfo> inStockInfoList = inStockInfoMapper.selectByExample(example);
            //判断
            if (inStockInfoList!= null){
                //循环
                for (InStockInfo inStockInfo : inStockInfoList) {
                    //获取库存表
                    Example example1 = new Example(ProductStock.class);
                    Example.Criteria criteria1 = example1.createCriteria();
                    criteria1.andEqualTo("pNum",inStockInfo.getPNum());
                    ProductStock productStock = productStockMapper.selectOneByExample(example1);
                    //不为空，代表存在
                    if (productStock != null ){
                        //修改库存表
                        productStock.setStock(productStock.getStock() + inStockInfo.getProductNumber());
                        productStockMapper.updateByPrimaryKey(productStock);

                        //修改入库表
                        inStock.setStatus(0);
                        inStock.setModified(new Date());
                        inStockMapper.updateByPrimaryKey(inStock);
                    }else {
                        //为空代表不存在库存，需要新增
                        productStock = new ProductStock();
                        productStock.setPNum(inStockInfo.getPNum());
                        productStock.setStock(Long.parseLong(inStockInfo.getProductNumber()+""));
                        productStockMapper.insert(productStock);
                    }
                }
            }
        }
    }
}
